/* DRAW.C */

/*
	Copyright (C) 2010 by Lesnikov Andrey <ozkriff@gmail.com>
	This file is part of ozkriff_game_2.

	ozkriff_game_2 is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	ozkriff_game_2 is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with ozkriff_game_2.  If not, see <http://www.gnu.org/licenses/>.

	See the COPYING file for more details.
*/

#include <stdbool.h>

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"

#include "defines.h"
#include "nograph.h"
#include "model.h"
#include "camera.h"
#include "gui.h"
#include "path.h"

#include "draw.h"


extern float	HEX[6*3];
extern camera	CAMERA;
extern uint	PLAYER;
extern float	HEX_IN;
extern float	HEX_EX;
extern model	mdl[130];
extern unit *	SELECTED_UNIT;
extern int	MODE;
extern cell	MAP[MAP_SIZE_X][MAP_SIZE_Y];
extern uint	aX;
extern uint	aY;
extern unit *	UNITS;
extern bool	CAN_GET_THERE[MAP_SIZE_X][MAP_SIZE_Y];
extern ushort	back_path_x[100];
extern ushort	back_path_y[100];
extern ushort	back_path_current;
extern int	SELECTED_BUTTON;
extern gui_button
		BUTTONS[100];
extern move	MOVE;
extern uint8_t	NET_MODE;
extern fight	FIGHT;
extern int	FIGHT_MODE;
extern GLuint	texture;




GLUquadricObj *GQO; //тестовый объект. потом удалить его.

int cursorX, cursorY; //координаты курсора

int PICKED_SMTH;
SDL_Surface *surface;
int video_flags; /* Flags to pass to SDL_SetVideoMode */

int SCR_WIDTH = 400;
int SCR_HEIGHT = 300;
int SCR_BPP = 32;

GLuint sky_texture[6]; //ID текстур неба. УДАЛИТЬ.

uint DRAW_ALL_PATH = 2;

//======================================================

void
translate(ushort y, ushort x)
{
	float ry, rx;
	map_to_real(x, y, &rx, &ry);
	
	glTranslatef(rx, ry, 0);
}



void
reshape(int w, int h)
{
	glViewport(0, 0, w, h);	// Reset The Current Viewport
	glMatrixMode(GL_PROJECTION);
	
	glLoadIdentity();
	//gluPerspective(45, (GLfloat)w/(GLfloat)h, 1, 100);
	gluPerspective(45, (GLfloat)w/(GLfloat)h, 0.01, 100);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	SCR_WIDTH = w;
	SCR_HEIGHT = h;
	
	init_textures();
}



void
draw_filled_hex()
{
#if(0)
	int i;
	for (i=0; i<6; i++) {
		glBegin(GL_TRIANGLES);
		{
			glVertex2f(0, 0);
			glVertex2f(0, HEX_EX);
			glVertex2f(HEX_IN, HEX_EX/2);
		}
		glEnd();
		glRotatef(60, 0, 0, 1);
	}
#else
	glVertexPointer(3, GL_FLOAT, 0, HEX);
	
	glDrawArrays(GL_POLYGON, 0, 6);
	
	//GLuint indexes[] = {0, 1, 2, 3, 4, 5};
	//glDrawElements(GL_LINE_LOOP, 6, GL_UNSIGNED_INT, indexes);
#endif
}




void
draw_wire_hex()
{
//	glLineStipple(1,0x00FF);
//	glEnable(GL_LINE_STIPPLE);

#if(0)
	glBegin(GL_LINE_STRIP);
	{
		glVertex3f(0,           HEX_EX, 0.01);
		glVertex3f(-HEX_IN, +HEX_IN/2, 0.01);
		glVertex3f(-HEX_IN, -HEX_IN/2, 0.01);
		glVertex3f(0,          -HEX_EX, 0.01);
		glVertex3f(HEX_IN, -HEX_IN/2, 0.01);
		glVertex3f(HEX_IN,  HEX_IN/2, 0.01);
		glVertex3f(0,           HEX_EX, 0.01);
	}
	glEnd();
#else
	glVertexPointer(3, GL_FLOAT, 0, HEX);
	glDrawArrays(GL_LINE_LOOP, 0, 6);
	//GLuint indexes[] = {0, 1, 2, 3, 4, 5};
	//glDrawElements(GL_LINE_LOOP, 6, GL_UNSIGNED_INT, indexes);
#endif
//	glDisable(GL_LINE_STIPPLE);
}


void
draw_quad(float x1, float y1, float x2, float y2)
{
	glBegin(GL_QUADS);
		glVertex2f(x1, y1);
		glVertex2f(x2, y1);
		glVertex2f(x2, y2);
		glVertex2f(x1, y2);
	glEnd();
}



void
draw_unit_header(unit *u)
{	
	glPushMatrix();

	glEnable(GL_BLEND);

	glTranslatef(0, 0, 0.8);
	glRotatef(CAMERA.horiz_angle+90, 0, 0, -1); //повернуть в сторону камеры
	glRotatef(90, 0, 1, 0);

	float size = 0.06;

	glPushMatrix();
	glTranslatef(-size*4, -size*4, -0.0001);
	if(u->player == 1)
		glColor4f(1, 0, 0, 0.6);
	else
		glColor4f(0, 0, 1, 0.6);
	draw_quad(0, -size*2, size*4, size*2);
	glPopMatrix();

	glPushMatrix();
	uint i;
	for(i=0; i < u->type->health; i++)
	{
		if(i<u->health)
			glColor3f(0, 0.6, 0);
		else
			glColor3f(0.6, 0, 0);
		draw_quad(0, 0, size, size);
		glTranslatef(-(size*1.2), 0, 0);
	}
	glPopMatrix();

	glTranslatef(0, size, 0);

	glPushMatrix();
	glColor3f(0, 0.5, 0.8);
	for(i=0; i < u->type->morale; i++)
	{
		if(i < u->morale)
			glColor3f(0, 0.6, 0.8);
		else
			glColor3f(0, 0.2, 0.4);
		draw_quad(0, 0, size, size);
		glTranslatef(-(size*1.2), 0, 0);
	}
	glPopMatrix();

	glTranslatef(0, size, 0);


	if(u->can_atack)
	{
		glColor3f(1, 0, 0);
		draw_quad(0, 0, size, size);
	}
	if(u->ap)
	{
		glColor3f(0, 0, 1);
		glTranslatef(0, size, 0);
		draw_quad(0, 0, size, size);
	}

	glDisable(GL_BLEND);

	glPopMatrix();
}



void
draw_character(unit *u)
{
	glPushMatrix();
	glTranslatef(u->x, u->y, 0.01); //slightly above the floor
	
	draw_unit_header(u);

	if(!strcmp(u->type->name, "arch"))	glColor3f(1, 0, 0);
	if(!strcmp(u->type->name, "atck"))	glColor3f(0, 1, 0);
	if(!strcmp(u->type->name, "def"))	glColor3f(0, 0, 1);
	if(!strcmp(u->type->name, "hunt"))	glColor3f(1, 1, 0);

	//draw model		
	glRotatef(90, 1, 0, 0); // because of blender exporter
	glRotatef(u->rot, 0, 1, 0); //individual character rotation
	glEnable(GL_TEXTURE_2D);
	draw_model(mdl[u->frame]);
	glDisable(GL_TEXTURE_2D);
	
#if(1) //outline
	if(u == SELECTED_UNIT)
	{
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
		glPolygonMode(GL_BACK, GL_LINE);

		glCullFace(GL_FRONT);
		glDepthFunc(GL_LEQUAL);

		glColor3f(1, 0, 0);
		draw_model(mdl[u->frame]);
		
		glDepthFunc(GL_LESS);
		glCullFace(GL_BACK);
		glPolygonMode(GL_BACK, GL_FILL);
	}
#endif
	
#if(0)	//model's shadow
	glScalef(1, 0.01, 1); //расплющить юнит, что б был похож на тень
	glColor4f(0, 0, 0, 0.5);
	draw_model(mdl[u->frame]);
#endif
	glPopMatrix();
}


//TODO. очень плохо. переделать. загружать отдельный .obj с небом
void
draw_sky()
{


	glPushMatrix();
	glScalef(50, 50, 50);
	glColor3f(1, 1, 1);
	
	glEnable(GL_TEXTURE_2D);
	
	
	// сторона 1
	glBindTexture(GL_TEXTURE_2D, sky_texture[1]);
	glBegin(GL_QUADS);
	//glColor3f(1, 0, 0);
	//glNormal3f(0.0f, -1.0f, 0.0f);
	glTexCoord2f(1, 1);
	glVertex3f(-1, -1, -1);
	glTexCoord2f(0, 1);
	glVertex3f(1, -1, -1);
	glTexCoord2f(0, 0);
	glVertex3f(1, -1,  1);
	glTexCoord2f(1, 0);
	glVertex3f(-1, -1,  1);
	glEnd();
	
	// сторона 2
	glBindTexture(GL_TEXTURE_2D, sky_texture[2]);
	glBegin(GL_QUADS);
	//glColor3f(0, 1, 0);
	//glNormal3f(0.0f, 1.0f, 0.0f);
	glTexCoord2f(0, 1);
	glVertex3f(-1,  1, -1);
	glTexCoord2f(0, 0);
	glVertex3f(-1,  1,  1);
	glTexCoord2f(1, 0);
	glVertex3f(1,  1,  1);
	glTexCoord2f(1, 1);
	glVertex3f(1,  1, -1);
	glEnd();
	
	// НИЖНЯЯ. ее вообще можно бы и удалить.
	//glBindTexture(GL_TEXTURE_2D, sky_texture[1]);
	//glBegin(GL_QUADS);
	//glColor3f(0, 0, 1);
	//glNormal3f(0.0f, 0.0f,-1.0f);
	glTexCoord2f(1, 0);
	glVertex3f(-1, -1, -1);
	glTexCoord2f(1, 1);
	glVertex3f(-1,  1, -1);
	glTexCoord2f(0, 1);
	glVertex3f(1,  1, -1);
	glTexCoord2f(0, 0);
	glVertex3f(1, -1, -1);
	glEnd();
	
	// сторона 3
	glBindTexture(GL_TEXTURE_2D, sky_texture[3]);
	glBegin(GL_QUADS);
	//glColor3f(1, 0, 1);
	//glNormal3f(1.0f, 0.0f, 0.0f);
	glTexCoord2f(0, 0);
	glVertex3f(1, -1, -1);
	glTexCoord2f(1, 0);
	glVertex3f(1,  1, -1);
	glTexCoord2f(1, 1);
	glVertex3f(1,  1,  1);
	glTexCoord2f(0, 1);
	glVertex3f(1, -1,  1);
	glEnd();
	
	// ВЕРХ
	//glBindTexture(GL_TEXTURE_2D, sky_texture[3]);
	//glBegin(GL_QUADS);
	//glColor3f(1, 1, 1);
	//glNormal3f(0.0f, 0.0f, 1.0f);
	glTexCoord2f(0, 0);
	glVertex3f(-1, -1,  1);
	glTexCoord2f(1, 0);
	glVertex3f(1, -1,  1);
	glTexCoord2f(1, 1);
	glVertex3f(1,  1,  1);
	glTexCoord2f(0, 1);
	glVertex3f(-1,  1,  1);
	glEnd();
	
	// сторона 4
	glBindTexture(GL_TEXTURE_2D, sky_texture[4]);
	glBegin(GL_QUADS);
	//glColor3f(1, 1, 0);
	//glNormal3f(-1.0f, 0.0f, 0.0f);
	glTexCoord2f(0, 1);
	glVertex3f(-1, -1, -1);
	glTexCoord2f(0, 0);
	glVertex3f(-1, -1,  1);
	glTexCoord2f(1, 0);
	glVertex3f(-1,  1,  1);
	glTexCoord2f(1, 1);
	glVertex3f(-1,  1, -1);
	
	glEnd();
	glPopMatrix();
	
	glDisable(GL_TEXTURE_2D);
}



//TODO разбить на кучу функций
void
draw_terrain()
{
	glPushMatrix();
	
	uint x, y;
	for (y=0; y< MAP_SIZE_Y; y++) {
		for (x=0; x<MAP_SIZE_X; x++) {
			glPushMatrix();
			glTranslatef(0, 0, 0.01);
			if (SELECTED_UNIT)
			{
#if(0)
				//это можно бы вынести отсюда и рисовать простым переносом.
				if (SELECTED_UNIT->mx == x && SELECTED_UNIT->my == y) {
					glColor3f(0.8, 0.3, 0.3);
					//gluDisk(GQO, HEX_IN*0.9, HEX_IN*1.15, 12, 1);
					gluDisk(GQO, HEX_IN*0.9, HEX_IN*1.15, 12, 1);
				}
#endif
				
				if(MODE == MODE_SELECT)
				{
					//рисует кружок над клетой, если мы можем дойти туда
					uint cost = MAP[x][y].move_cost;
					uint ap = SELECTED_UNIT->ap;
					if(0)
					{
						uint AP = SELECTED_UNIT->type->ap;
						//glColor3f(0.6, 0.6, 0.6); //default
						if(cost <= ap+AP*3 &&cost > ap+AP*2)glColor3f(0.5, 1, 1);
						if(cost <= ap+AP*2 && cost > ap+AP) glColor3f(1.0, 0.5, 0.5);
						if(cost <= ap+AP   && cost > ap)    glColor3f(0.5, 0.5, 1.0);
						if(cost <= ap      && cost > 0)	    glColor3f(0.5, 1.0, 0.5);
						gluDisk(GQO, HEX_IN*0.01, HEX_IN*0.3, 6, 1);
					}
					else
					{
						if(cost <= ap && cost > 0)
						{
							glPushMatrix();
							glTranslatef(0, 0, 0.001);
							//glColor3f(0.8, 0.3, 0.3);
							//gluDisk(GQO, HEX_IN*0.01, HEX_IN*0.3, 6, 1);
							glColor3f(1, 0, 0);
							draw_filled_hex();
							glPopMatrix();
						}
					}
				}
			}
			if (PICKED_SMTH && aX == x && aY == y)
			{
				glColor3f(0.3, 0.8, 0.3);
				gluDisk(GQO, HEX_IN*0.95, HEX_IN*1.1, 12, 1);
			}
			glPopMatrix();

		
			glColor3ub(255, 255, 255); //errorcolor
		//	if(MAP[x][y].type == TERRAIN_NORMAL)	glColor3ub(  2,  80,  55);
			if(MAP[x][y].type == TERRAIN_NORMAL)	glColor3ub(160, 200, 100);
			if(MAP[x][y].type == TERRAIN_ROAD) 	glColor3ub(195, 176, 192);
		//	if(MAP[x][y].type == TERRAIN_FOREST)	glColor3ub(  1,  50,  32);
			if(MAP[x][y].type == TERRAIN_FOREST)	glColor3ub(160, 200, 100);
			if(MAP[x][y].type == TERRAIN_WATER)	glColor3ub(  0, 149, 182);
		//	if(MAP[x][y].type == TERRAIN_HILLS)	glColor3ub(1, 0.6, 0);
		//	if(MAP[x][y].type == TERRAIN_MOUNT)	glColor3ub(0.8, 0.6, 0);
			glEnableClientState(GL_VERTEX_ARRAY);
			
#if(1)			// if can atack this enemy //TODO вынести отсюда //рисовать подругому
			if (MODE == MODE_SELECT
					&& SELECTED_UNIT  && SELECTED_UNIT->can_atack
					&& MAP[x][y].unit && MAP[x][y].unit->player != PLAYER
					&& get_distance(SELECTED_UNIT->mx, SELECTED_UNIT->my, x, y) <= SELECTED_UNIT->attack_distance
			){
				glColor3f(1, 0, 0);
			}
#endif	
	
#if(0) 			//гексы на пути будут подсвечены
			//можно делать проверку на то, что точка вообще в нужном районе для оптимизации
			if (SELECTED_UNIT && check_line_hex_intersects(SELECTED_UNIT->mx, SELECTED_UNIT->my,  aX,aY,  x,y))
				glColor3f(0, 1, 0);
#endif		
			draw_filled_hex();

#if(1)
			if(MAP[x][y].type == TERRAIN_FOREST)
			{
				glEnable(GL_BLEND);
				glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
				glColor4ub(  1,  50,  32, 155);
				glPushMatrix();
				{
					glRotatef(30, 0, 0, 1);
					glTranslatef(0.2, 0.2, 0);
					gluCylinder(GQO, 0.15, 0.001, 0.6, 3, 1);

					glTranslatef(-0.4, 0, 0);
					gluCylinder(GQO, 0.15, 0.001, 0.6, 3, 1);
					
					glTranslatef(0.2, -0.4, 0);
					gluCylinder(GQO, 0.15, 0.001, 0.6, 3, 1);
				}
				glPopMatrix();
				glDisable(GL_BLEND);
			}
#endif

#if(1)			//draw wire
			glColor3f(0.5, 0.5, 0.5);
			draw_wire_hex();
#endif
			glDisableClientState(GL_VERTEX_ARRAY);
			glTranslatef(2*HEX_IN, 0, 0);
		}
		if (y%2 == 0)
			glTranslatef(-HEX_IN, 1.5*HEX_EX, 0);
		else
			glTranslatef(+HEX_IN, 1.5*HEX_EX, 0);
		glTranslatef(-(2*HEX_IN *MAP_SIZE_X), 0, 0);
	}
	
	glPopMatrix();
}



//TODO вынести обработку тумана войны отсюда
void
draw_characters()
{
	unit* u = UNITS;
	while(u != NULL)
	{
		if(MAP[u->mx][u->my].fog)
			draw_character(u);
		u = u->next;
	}
}



void
draw_fog_of_war()
{
	ushort x, y;
	float rx, ry;

	glEnable(GL_BLEND);
	glEnableClientState(GL_VERTEX_ARRAY);
	glColor4f(0, 0, 1, 0.3);

	for (x=0; x<MAP_SIZE_X; x++)
	{
		for (y=0; y<MAP_SIZE_Y; y++)
		{
			if(MAP[x][y].fog <= 0)
			{
				glPushMatrix();
				map_to_real(x, y, &rx, &ry);
				glTranslatef(rx, ry, 0.002);
				draw_filled_hex();
				glPopMatrix();
			}
		}
	}

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisable(GL_BLEND);
}



void
draw_can_get (unit *u)
{
	ushort x, y;
	float rx, ry;
	
	if(!u)	return;
		
	glEnable(GL_BLEND);
	glEnableClientState(GL_VERTEX_ARRAY);
	glColor4f(0, 1, 0.5, 0.4);
	//glColor4f(1, 1, 1, 0.3);

	for (x=0; x<MAP_SIZE_X; x++)
	{
		for (y=0; y<MAP_SIZE_Y; y++)
		{
			if(!MAP[x][y].unit && MAP[x][y].move_cost <= u->ap)
			{
				glPushMatrix();
				map_to_real(x, y, &rx, &ry);
				glTranslatef(rx, ry, 0.03);
				draw_filled_hex();
				glPopMatrix();
			}
		}
	}

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisable(GL_BLEND);
}



//рисует белую линию от выбранной ячейки до активной(куда тыкает мышка)
void
line()
{
	if (!SELECTED_UNIT)
		return;

	glLineWidth(4);

	glColor3f(0, 0, 1);
	glBegin(GL_LINES);
	{
		float rx, ry;
		
		map_to_real(aX, aY, &rx, &ry);
		glVertex3f(rx, ry, 0);
		map_to_real(SELECTED_UNIT->mx, SELECTED_UNIT->my, &rx, &ry);
		glVertex3f(rx, ry, 0);
	}
	glEnd();

	glLineWidth(1);
}



void
draw_plane()
{
	//типа земля или чего то такое.
	glPushMatrix();
	glTranslatef(0, 0, -0.2);
	glScalef(100, 100, 100);
	if(PLAYER == 1)
		glColor3f(1, .7, .7);
	else
		glColor3f(.7, .7, 1);
	//glColor3f(1, 1, 1);
	glBegin(GL_QUADS);
	{
		glVertex2f(-1, -1);
		glVertex2f(+1, -1);
		glVertex2f(+1, +1);
		glVertex2f(-1, +1);
	}
	glEnd();
	glPopMatrix();
}



void
draw_path(ushort x, ushort y)
{
	if (MODE != MODE_SELECT)
		return;

	if(!CAN_GET_THERE[x][y])
		return;

	//if(!SELECTED_UNIT)
	if(!SELECTED_UNIT || MAP[x][y].unit)
	//if(!PICKED_SMTH || !SELECTED_UNIT || MAP[x][y].unit)
		return;

	if(SELECTED_UNIT->type->terrain[MAP[x][y].type] > SELECTED_UNIT->type->ap)
		return;

	//if((x<0) && (x>=MAP_SIZE_X) && (y<0) && (y>=MAP_SIZE_Y))
	if((x>=MAP_SIZE_X) && (y>=MAP_SIZE_Y))
		return;

	//todo переписать. КРИВО
	fill_map(SELECTED_UNIT); //FUCK. может это поомжет?

	glLineWidth(3);

	get_path(SELECTED_UNIT, x, y);
	//glColor3f(0, 0.8, 0);

	int i;
	for(i = back_path_current-1; i > 0; i--)
	{
		float rx, ry;
		if(MAP[back_path_x[i-1]][back_path_y[i-1]].move_cost <= SELECTED_UNIT->ap)
			glColor3f(0, 0.8, 0);
		else
			glColor3f(0.8, 0, 0);

		glBegin(GL_LINES);
		map_to_real(back_path_x[i], back_path_y[i], &rx, &ry);
		glVertex3f(rx, ry, 0.04);
		map_to_real(back_path_x[i-1], back_path_y[i-1], &rx, &ry);
		glVertex3f(rx, ry, 0.04);
		glEnd();
	}
	glLineWidth(1);
}






void
handle_mouse_events(SDL_Event E)
{
	if(E.type){};

	if (SELECTED_BUTTON != -1)
	{
		printf("%s\n", BUTTONS[ SELECTED_BUTTON ].name);
		return;
	}

	//отключил, т.к. сначало надо реализовать "западни"
#if(0)	//if press button 1 while moving..
	//если нажать ЛКМ во время движения, то сразу окажемся в конечной точке
	//может конфликтовать с концепцией засад
	if(MODE == MODE_MOVE)
	{
		MODE = MODE_SELECT;
		MOVE.unit->mx = back_path_x[0];
		MOVE.unit->my = back_path_y[0];
		map_to_real(MOVE.unit->mx, MOVE.unit->my, &(MOVE.unit->x), &(MOVE.unit->y));
		MAP[MOVE.unit->mx][MOVE.unit->my].unit = MOVE.unit;
		fill_map(MOVE.unit);
		MOVE.unit->frame = 98;
		MOVE.unit = NULL;
		return;
	}
#endif
	
	if(NET_MODE == MODE_PASSIVE)
		return;
	
	if (!PICKED_SMTH || MODE != MODE_SELECT)
		return;

	if (MAP[aX][aY].unit) { //если тут хто то есть
		//если это наш юнит
		if (MAP[aX][aY].unit->player == PLAYER) {
			//если опять кликнуть на уже выделенном юните
			// - камера отцентрируется на нем
			if (SELECTED_UNIT && MAP[aX][aY].unit == SELECTED_UNIT) {
				map_to_real(aX, aY, &(CAMERA.x), &(CAMERA.y));
				CAMERA.y = -CAMERA.y;
				CAMERA.x = -CAMERA.x;
			}else{
				//select character
				SELECTED_UNIT = MAP[aX][aY].unit;
				//fill_map(&q, aY, aX);
				fill_map(SELECTED_UNIT);
			}
		} else if (SELECTED_UNIT
				&& SELECTED_UNIT->can_atack
				&& get_distance(aX, aY, SELECTED_UNIT->mx, SELECTED_UNIT->my)
						<= SELECTED_UNIT->attack_distance)
		{
			// KILL

			SELECTED_UNIT->can_atack = false;
			FIGHT.u1 = SELECTED_UNIT;
			FIGHT.u2 = MAP[aX][aY].unit;
			MODE = MODE_FIGHT;
			FIGHT_MODE = MODE_FIGHT_1;

			calculate_damage();
						
			send_to_server(NET_FIGHT);
			send_to_server(SELECTED_UNIT->mx);
			send_to_server(SELECTED_UNIT->my);
			send_to_server(aX);
			send_to_server(aY);
		}
	} else { //если тут никого нет
		//но таки кто то выбран
		if (SELECTED_UNIT) {
			// try move selected character
			fill_map(SELECTED_UNIT);
			if (MAP[aX][aY].move_cost <= SELECTED_UNIT->ap) 
			{
				//if character has requested action points
				//SELECTED_UNIT->ap -= MAP[aX][aY].move_cost; //TODO убирать поэтапно
				SELECTED_UNIT->ap = 0;
				//get_path(SELECTED_UNIT->mx, SELECTED_UNIT->my, aX, aY); //TODO изменить порядок
				get_path(SELECTED_UNIT, aX, aY); //TODO изменить порядок
				MODE = MODE_MOVE;
				MOVE.step_count = 0;
				MOVE.unit = SELECTED_UNIT;
				MAP[SELECTED_UNIT->mx][SELECTED_UNIT->my].unit = NULL;

				//update_fog(MOVE.unit->type->see, MOVE.unit->mx, MOVE.unit->my, -1);
				
				send_to_server(NET_MOVE);
				send_to_server(SELECTED_UNIT->mx);
				send_to_server(SELECTED_UNIT->my);
				send_to_server(aX);
				send_to_server(aY);
			}
			
		}
	}
	
}



void
init_opengl()
{
	glEnable(GL_TEXTURE_2D);
	glShadeModel(GL_SMOOTH);
	
	glClearColor(0, 0, 0, 1);
	glClearDepth(1.0f);
	glEnable(GL_DEPTH_TEST);
	
	//glEnable(GL_LIGHTING);
	glEnable(GL_AUTO_NORMAL);
	glEnable(GL_COLOR_MATERIAL);
	glEnable(GL_LIGHT0);
	glEnable(GL_NORMALIZE);
	glEnable(GL_BLEND);
	//float POS[] = {0, 1, 0, 0};
	//glLightfv(GL_LIGHT0, GL_POSITION, POS);
	
	glDepthFunc(GL_LEQUAL);     /* The Type Of Depth Test To Do */

	/* Really Nice Perspective Calculations */
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
	
	glEnable(GL_CULL_FACE);
	//glFrontFace(GL_CW);
	glCullFace(GL_BACK);
	
	//glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, GL_FALSE);
}




void
init_textures()
{
	texture = load_texture("../img/CUBE_WARRIOR.bmp");
	//texture = load_texture("../img/CUBE_WARRIOR.PNG");
	//texture = load_texture("../img/CUBE_WARRIOR.GIF");
	
	sky_texture[1] = load_texture("../img/sky1.bmp");
	sky_texture[2] = load_texture("../img/sky2.bmp");
	sky_texture[3] = load_texture("../img/sky3.bmp");
	sky_texture[4] = load_texture("../img/sky4.bmp");
}



void
init_models()
{
	int i;
	for (i = 0; i < 121; i++) {
		char obj_file_name[100];
		sprintf(obj_file_name, "../mdl/qube_warrior/CUBE_WARRIOR_000%03i.obj", i+1);
		mdl[i] = read_obj_file(obj_file_name);
	}
}



void
draw_all_paths()
{
	int x, y;
					
	for(x=0; x<MAP_SIZE_X; x++)
		for(y=0; y<MAP_SIZE_Y; y++)
		{
			if(DRAW_ALL_PATH == 1)
				draw_path(x, y);
			if(DRAW_ALL_PATH == 2)
				if(MAP[x][y].move_cost <= SELECTED_UNIT->ap)
					draw_path(x, y);
		}
}



void
draw()
{
	glClearColor(0, 0, 0, 1);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
	set_camera();

	//draw_sky();

	//line();
	//draw_plane();

	if(SELECTED_UNIT)
	//if(0)
	{
		if(PICKED_SMTH)
		{
			draw_path(aX, aY);
		}
		if(DRAW_ALL_PATH != 0)
		{
			draw_all_paths();
		}
	}

	draw_terrain();
	draw_characters();

	draw_fog_of_war();
	
	draw_can_get(SELECTED_UNIT);
	
	draw_interface();

	SDL_GL_SwapBuffers();
}




